package com.laiketui.online.message.websocket;

import com.alibaba.fastjson.JSON;
import com.laiketui.online.message.common.consts.OnlineMessageConst;
import com.laiketui.core.common.SplitUtils;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 控制层
 */
@Component
@ServerEndpoint("/onlineMessage/{sendId}/{receiveId}/{storeType}")
public class WebSocketServer {
    public final Logger logger = LoggerFactory.getLogger(this.getClass());
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap =
            new ConcurrentHashMap<>();

    private Session session;

    private String sendId;

    private String receiveId;

    private String storeType;

    @OnOpen
    public void onOpen(Session session, @PathParam("sendId") String sendId,
                       @PathParam("receiveId") String receiveId, @PathParam("storeType") String storeType) {

        String key =getStoreType(storeType) +  sendId + "," + receiveId;
        logger.info("链接信息,sendId:{},receiveId,{}",sendId,receiveId);
        logger.info("打开前链接对象：{}",JSON.toJSONString(webSocketMap));
        WebSocketServer webSocketServer = webSocketMap.get(key);
        if(webSocketServer == null ){
            this.storeType = getStoreType(storeType);
            this.session = session;
            this.sendId = sendId;
            this.receiveId = receiveId;
            webSocketMap.put(key, this);
        } else {
            if(!webSocketServer.session.isOpen()){
                webSocketMap.put(key, this);
            }
        }
        logger.info("打开前链接对象：{}",JSON.toJSONString(webSocketMap));
        logger.info("websocket 有新的连接,连接数:{}", webSocketMap.size());
    }

    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(storeType + sendId + SplitUtils.DH + receiveId);
        logger.info("链接-{}-断开",sendId + SplitUtils.DH + receiveId);
        logger.info("websocket 有连接断开,剩余连接数:{}", webSocketMap.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("session：{},服务器端接受到的消息：{}",session.getQueryString(),message);
        logger.info("webSocketMap size :{}",webSocketMap.size());
    }
    /**
     * 配置错误信息处理
     * @param session
     * @param t
     */
    @OnError
    public void onError(Session session, Throwable t) {
        webSocketMap.remove(sendId + SplitUtils.DH + receiveId);
        logger.info("【websocket消息】出现未知错误 ");
        t.printStackTrace();
    }

    public void sendMessage(String key, String text) {
        try {
            WebSocketServer webSocketServer = webSocketMap.get(key);

            if(webSocketServer == null ){
                logger.error(" {} - 通道不存在",key);
                return;
            }

            if(webSocketServer.session.isOpen()){
                webSocketServer.session.getAsyncRemote().sendText(text);
                logger.error("发送消息成功,key:{},content:{}", key, text);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送失败：{}",e.getMessage());
            logger.error("发送消息失败,key:{},content:{}", key, text);
        }
    }
    //消息来源
    private String getStoreType(String storeType){
        switch (storeType){
            case OnlineMessageConst.StoreSource.LKT_LY_001:
                return OnlineMessageConst.StoreType.APPLET;
            case OnlineMessageConst.StoreSource.LKT_LY_002:
                return OnlineMessageConst.StoreType.APP;
            case OnlineMessageConst.StoreSource.LKT_LY_006:
                return OnlineMessageConst.StoreType.PcStore;
            case OnlineMessageConst.StoreSource.LKT_LY_007:
                return OnlineMessageConst.StoreType.H5;
            case OnlineMessageConst.StoreSource.LKT_LY_008:
                return OnlineMessageConst.StoreType.PcMch;
            default:
                return "";
        }
    }
}
